package m4_routting;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Scanner;


//路由键模式---生产者
public class Producer {

    public static void main(String[] args) throws Exception{

        //1.建立连接
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("192.168.64.140");
        cf.setPort(5672);
        cf.setUsername("admin");
        cf.setPassword("admin");

        Connection conn = cf.newConnection();
        Channel ch = conn.createChannel();

        //2.生产者要通过channel定义一个交换机 （fanout类型） 给这个交换机取个名字direct_logs
        //ch.exchangeDeclare("direct_logs","direct");
        ch.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);

        //3.生产者向交换机发送消息
        //用一个死循环
        while (true){
            System.out.println("输入消息： ");
            String msg = new Scanner(System.in).nextLine();
            System.out.println("输入路由键关键词：");
            String key = new Scanner(System.in).nextLine();

            if(msg.equals("exit")){
                break;
            }

            ch.basicPublish("direct_logs",
                            key,//路由键 关键词
                            null,
                          msg.getBytes());
            System.out.println("消息已发送： "+msg);
        }

        conn.close();
    }


}
